/**
 * 工程axios 拦截器
 */
import axios from 'axios';
import { message } from 'ant-design-vue';
import store from '../store/index';
import router from '../router/index';
import i18n from '@/locales';
import { maccApi } from '../../../utils';

const ErrorMsg = {
  400: i18n.t('error.400'),
  401: i18n.t('error.401'),
  403: i18n.t('error.403'),
  404: i18n.t('error.404'),
  405: i18n.t('error.405'),
  408: i18n.t('error.408'),
  500: i18n.t('error.500'),
  501: i18n.t('error.501'),
  502: i18n.t('error.502'),
  503: i18n.t('error.503'),
  504: i18n.t('error.504'),
  505: i18n.t('error.505'),
};
axios.defaults.timeout = 30000;

/**
 * http request 拦截器
 */
axios.interceptors.request.use(
  (config) => {
    config.headers = {
      'Content-Type': 'application/json',
    };
    // appendTokenToUrl(config);
    printRequest(config);
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

/**
 * http response 拦截器
 */
axios.interceptors.response.use(
  (response) => {
    if (response.data.code === 3) {
      message.info(i18n.t('error.logTimeout'), 1, () => {
        // router.replace('login');
        store.commit('User/CLEAR_TOKEN');
        store.commit('User/TOP_LOGINOUT');

        if (process.env.VUE_APP_MACC_CLOUD_ENV === 'private') {
          location.href = '/webproxy/private/logout';
        } else {
          location.href = '/webproxy/sso/logout';
        }
      });
    }

    const responseCode = response?.data?.code;
    // tommy 24.3.25 避免重复报错
    // tommy 24.4.17 5, 36是没有权限。3是logout
    // TOKEN_INVALID(Component.COMMON, 3, "Token 无效."),
    // TOKEN_OVERDUED(Component.COMMON, 4, "Token 已经过期."),
    // API_UNAUTH(Component.COMMON, 5, "您没有权限执行该操作."),
    // API_UNAUTH_BY_TENANT(Component.COMMON, 36, "你没有当前租户下任何网络的权限，请切回默认租户"),
    // 20 后端模块异常
    if (response && [3, 4, 5, 20, 36, 50].includes(responseCode)) {
      const currentCode = responseCode;
      const current = new Date().getTime();
      const { code, createtime } = store.state.User?.lastRequestFailObj;
      if (code) {
        console.log(`current: ${current}, createtime: ${createtime},
           current - createtime = ${current - createtime}`);
        if (code === currentCode && current - createtime < 200) {
          response.data.code = 0;
        }
      }
      store.commit('User/SET_LAST_REQUEST_FAIL', {
        code: currentCode,
        createtime: current,
      });
    }

    if (response && response.data.code < -1 && response.data.code != -98) {
      //接口访问404
      let responseErr = {
        code: response.data.code,
        msg: `${i18n.t('error.requestFailCode')}${response.data.errorCode}`,
      };
      //responseErr = JSON.stringify(responseErr);
      if (process.env.VUE_APP_MACC_CLOUD_ENV !== 'private') {
        message.error(`${i18n.t('error.requestFailLabel')}${responseErr.msg}`);
      }
    }
    response = checkFilterRespone(response);

    response = JSON.parse(formatterSoftVersion(JSON.stringify(response)));

    return response;
  },
  (error) => {
    if (error.response && error.response.status == 403) {
      const ret = error.response.data;
      if (ret.code == -1) {
        if (process.env.VUE_APP_MACC_CLOUD_ENV === 'private') {
          router.push('login');
        } else {
          const href =
            ret.data.ssoJump +
            '?rewrite=off&back=' +
            encodeURIComponent(location.href);
          location.href = href;
        }
        return false;
      }
    }
    const config = error.config;
    // 如果config不存在或未设置重试选项，请拒绝
    if (!config || !config.retry) {
      const msg =
        error.response && error.response.status
          ? ErrorMsg[error.response.status]
          : i18n.t('error.requestFail');

      //message.error(`请求出错:${msg.toString()}`);
      return Promise.resolve({ code: -1, msg: msg });
    }
    // 设置变量跟踪重试次数
    config.__retryCount = config.__retryCount || 0;
    // 检查是否已经达到最大重试总次数
    if (config.__retryCount >= config.retry) {
      // 抛出错误信息
      return Promise.resolve({ code: -1, msg: i18n.t('error.requestTimeout') });
    }
    // 增加请求重试次数
    config.__retryCount += 1;
    // 创建新的异步请求
    const backoff = new Promise(function (resolve) {
      setTimeout(function () {
        resolve();
      }, config.retryDelay || 1);
    });
    // 返回axios信息，重新请求
    return backoff.then(function () {
      return axios(config);
    });
  }
);

// function appendTokenToUrl(config) {
//   if (config.url.indexOf('/login') != -1) {
//     return;
//   }
//   const {
//     User: { access_token },
//   } = store.state;
//   let symbol = config.url.indexOf('?') == -1 ? '?' : '&';
//   config.url += `${symbol}access_token=${access_token}`;
// }

//打印请求
function printRequest(config) {
  if (process.env.NODE_ENV != 'development') return;
  if (config.method == 'post') {
    console.log(`%c请求地址 ==> ${config.data.api}`, 'color:#65c366');
  }

  console.log(
    `%c请求类型 ==> ${config.method} ${
      config.method == 'get' ? JSON.stringify(config.params) : ''
    }`,
    'color:#65c366'
  );
}

/**
 * 替换版本号
 * @param {*} response
 * @returns
 */
function formatterSoftVersion(response) {
  response = checkSoftAndFormatter(response, 'softwareVersion');
  response = checkSoftAndFormatter(response, 'recommendSoftwareVersion');
  response = checkSoftAndFormatter(response, 'softVersion');
  response = checkSoftAndFormatter(response, 'deviceSoftware');
  return response;
}

function checkSoftAndFormatter(response, key) {
  const testPattern = new RegExp('"' + key + '":', 'g');
  if (testPattern.test(response)) {
    const matchPattern = new RegExp('"' + key + '":"(.*?)"', 'g');
    const softwareVersion = response.match(matchPattern);
    for (let i = 0; i < softwareVersion.length; i++) {
      const oldsoftwareVersion = softwareVersion[i].split(':');
      const newsoftwareVersion = checkSoftVersion(
        oldsoftwareVersion[1].replace(/"/g, '')
      );
      response = response.replace(
        softwareVersion[i],
        `"${key}":"${newsoftwareVersion}","real_${key}":${oldsoftwareVersion[1]}`
      );
    }
  }
  return response;
}

function checkSoftVersion(softVersion) {
  if (softVersion.startsWith('ReyeeOS')) {
    return softVersion.split(';')[0];
  } else {
    return softVersion;
  }
}

function checkFilterRespone(response) {
  const noFilterUrls = [
    maccApi.CLOUD_USERAGREEMENT_LASTVERSION_GET_API.split('?')[0],
  ];
  const currentUrl = response.config.url.replace('/webproxy/common/api?', '');
  if (noFilterUrls.includes(currentUrl)) {
    return response;
  } else {
    const newResponse = JSON.parse(
      JSON.stringify(response).replace(/(<([^>]+)>)/gi, '')
    );
    return newResponse;
  }
}
